package com.my.test.zookeeper;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;

import java.io.IOException;

/**
 * Created by Administrator on 2017-1-18.
 */
public class ZKClient {
	
    public ZooKeeper getZKClient(String addres){
        // 创建一个与服务器的连接
        try {
            return new ZooKeeper(addres, 10000, new Watcher() {
                // 监控所有被触发的事件
//				@Override
                public void process(WatchedEvent event) {
                    System.out.println("已经触发了" + event.getType() + "事件！");
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public void createNode(ZooKeeper zk,String nodePath,String nodeContext){
		// 创建一个目录节点
		 try {
			zk.create(nodePath, nodeContext.getBytes(), Ids.OPEN_ACL_UNSAFE,
			   CreateMode.PERSISTENT);
			 // 创建一个子目录节点
			System.out.println(new String(zk.getData(nodePath,false,null)));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public String getNodeData(ZooKeeper zk,String nodePath){
		try {
			return new String(zk.getData(nodePath,false,null));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	public void UpdateNodeData(ZooKeeper zk,String nodePath,String nodeContext) throws Exception{
		if(null!=zk.exists(nodePath, true)){
			zk.setData(nodePath,nodeContext.getBytes(),-1);
		}
	}
	public void deleteNode(ZooKeeper zk,String nodePath) throws Exception{
		if(null!=zk.exists(nodePath, true)){
			zk.delete(nodePath,-1); 
		}
	}
	public static void main(String[] args) throws Exception {
		ZKClient z = new ZKClient();
		ZooKeeper z1 = z.getZKClient("192.168.182.128:2181");
//		z.createNode(z1, "/hzb", "hzb");
		System.out.println(z.getNodeData(z1, "/hzb"));
		ZooKeeper z2 = z.getZKClient("192.168.182.133:2181");
//		z.createNode(z2, "/hzb", "hzb2");
		System.out.println(z.getNodeData(z2, "/hzb"));
		
		
		z.UpdateNodeData(z1, "/hzb", "update hzb");
		System.out.println("update z1:"+z.getNodeData(z1, "/hzb"));
		System.out.println("update z2:"+z.getNodeData(z2, "/hzb"));
//		ZooKeeper z3 = z.getZKClient("192.168.182.134:2181");
//		z.createNode(z2, "/hzb", "hzb3");
	}
}
